package com.fankui.gulimall.product.service.impl;

import com.fankui.common.utils.PageUtils;
import com.fankui.common.utils.Query;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.fankui.gulimall.product.dao.CategoryDao;
import com.fankui.gulimall.product.entity.CategoryEntity;
import com.fankui.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> findTreeList() {
        List<CategoryEntity> list = baseMapper.selectList(null);
        List<CategoryEntity> categoryEntityList = list.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .peek(categoryEntity -> categoryEntity.setChildren(findChildrenList(categoryEntity, list)))
                .sorted(Comparator.comparingInt(CategoryEntity::getSort))
                .collect(Collectors.toList());
        return categoryEntityList;
    }

    private List<CategoryEntity> findChildrenList(CategoryEntity menu, List<CategoryEntity> categoryEntityList) {
        List<CategoryEntity> childrenList = categoryEntityList.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(menu.getCatId()))
                .peek(categoryEntity -> categoryEntity.setChildren(findChildrenList(categoryEntity, categoryEntityList)))
                .sorted(Comparator.comparingInt(CategoryEntity::getSort))
                .collect(Collectors.toList());
        return childrenList;
    }
}